﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Musicman.Common.Entities;
using Musicman.Business;

namespace MusicmanWeb.USER
{
    public partial class FileStats : MusicmanPage
    {
        override protected void Page_Load(object sender, EventArgs e)
        {
            ReddirectNonActiveSession();
            
            long fileId = 0;
            if (Int64.TryParse(Request["SearchFileID"], out fileId))
            {
                BindSearchFile(fileId);
            }            
        }

        protected void RateFile_Command(object sender, CommandEventArgs e)
        {
            long sFielId = Int64.Parse(e.CommandArgument.ToString());
            int rating = Int32.Parse(fileRatingRB.SelectedValue);
            SearchFileManager.Instance.UpdateFileStats(sFielId, rating);
            BindSearchFile(sFielId);
        }

        private void BindSearchFile(long fileId)
        {
            SearchFile sf = null;
            if (fileId > 0)
            {
                sf = SearchFileManager.Instance.GetSearchFile(fileId);
            }
            else
            {
                List<SearchFile> cachedFiles = Cache["searchresult"] as List<SearchFile>;
                if (cachedFiles != null)
                {
                    sf = cachedFiles.Find(delegate(SearchFile sf1) { return sf1.SearchFileID == fileId; });
                }
            }
            if (sf != null)
            {
                sf.Statistics = SearchFileManager.Instance.LoadFileStatistics(fileId);
                this.fnameLbl.InnerText = sf.Name;
                this.fpathLbl.InnerText = String.Format("{0}\\{1}", sf.FilePath, sf.Name);
                this.sizeLbl.InnerText = Musicman.Common.Utilities.Converter.LengthMB(sf.Length);
                this.downloadsLbl.InnerText = sf.Statistics.TotalDownloads.ToString();
                this.ratedLbl.InnerText = sf.Statistics.TotalVoted.ToString();
                this.ratingLbl.InnerText = sf.Statistics.Rating.ToString();
                this.rateFileLB.CommandArgument = sf.SearchFileID.ToString();
                this.download.HRef = String.Format("GetFile.axd?SEARCHFILEID={0}", sf.SearchFileID);
            }
        }
    }
}
